﻿using Newtonsoft.Json;
using Pay.Cache;
using Pay.Common.Encrypt;
using Pay.Container;
using Pay.Model.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace Pay.Api.App_Start
{
    public class ApiAuthorizeAttribute : System.Web.Http.Filters.AuthorizationFilterAttribute
    {

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
            var attr = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>();
            if (attr.Any())
            {
                return;
            }
            else//取redis
            {

                if (actionContext.Request.Headers.Contains("token"))
                {
                    var token = actionContext.Request.Headers.GetValues("token").FirstOrDefault();
                    //可能需要加入解密

                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        try
                        {
                            //解密
                            //var userStr = DesEncrypt.DecryptDES(token, ConfigurationManager.AppSettings["encrypt:key"]);
                            //var userCookie = JsonConvert.DeserializeObject<AuthInfo>(token);
                            //获取redis中的user
                            var instance = LocManager.Resolve<ICacheManager>();
                            var user = instance.Get<UserInfo>(token);
                            if (user == null)
                            {
                                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("请求非法"));

                            }
                            else
                            {
                                actionContext.RequestContext.RouteData.Values.Add("userinfo", user);
                                //刷新过期时间
                                instance.Set(token, user, TimeSpan.FromDays(1));
                            }
                        }
                        catch(Exception ex)
                        {
                            actionContext.Response= actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("请求非法"));
                        }

                    }
                    else
                    {
                        actionContext.Response= actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("请求非法"));
                    }

                }
                else
                {
                  actionContext.Response=  actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new HttpError("请求非法"));
                }
            }

        }
    }
}
